package com.guapi.service;

import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import com.guapi.model.Content;
import com.guapi.model.ContentSearchResult;
import com.guapi.model.Tag;

public class DomQueryResultUnmarshaller implements QueryResultUnmarshaller {
	

	public ContentSearchResult unmarshall(InputStream inputStream) throws ApiUnmarshallException {
		ContentSearchResult result = new ContentSearchResult();
		
		try {
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
	        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
	        Document doc = docBuilder.parse (inputStream);
	
	        doc.getDocumentElement ().normalize ();
	
	        Element search = (Element) doc.getElementsByTagName("search").item(0);
	        
	        result.setCount(intAttribute(search.getAttribute("count")));
			result.setStartIndex(intAttribute(search.getAttribute("start-index")));
			
			Element results = (Element) search.getElementsByTagName("results").item(0);
			populateContentList(result, results);
	           
	    }catch (SAXParseException e) {
	    	throw new ApiUnmarshallException("Could not unmarshall", e);
	    }catch (SAXException e) {
	    	throw new ApiUnmarshallException("Could not unmarshall", e);    }catch (Throwable t) {
	    }
		
		return result;
	}

	private void populateContentList(ContentSearchResult result, Element results) {
		NodeList contentItems = results.getElementsByTagName("content");
		result.setContentList(new ArrayList<Content>());
		for (int x = 0; x < contentItems.getLength(); x++) {
			Element contentElement = (Element) contentItems.item(x);
			Content content = new Content();
			content.setApiUrl(contentElement.getAttribute("api-url"));
			content.setId(intAttribute(contentElement.getAttribute("id")));
			content.setType(contentElement.getAttribute("type"));
			content.setWebUrl(contentElement.getAttribute("web-url"));
			
			content.setTags(new ArrayList<Tag>());
			
			NodeList tags = ((Element)contentElement.getElementsByTagName("tagged-with").item(0)).getElementsByTagName("tag");
			for (int i = 0; i < tags.getLength(); i++) {
				Element tagElement = (Element) tags.item(i);
				Tag tag = new Tag();
				tag.setApiUrl(tagElement.getAttribute("api-url"));
				tag.setFilter(tagElement.getAttribute("filter"));
				tag.setName(tagElement.getAttribute("name"));
				tag.setType(tagElement.getAttribute("type"));
				tag.setWebUrl(tagElement.getAttribute("web-url"));
				content.getTags().add(tag);
			}
			
			result.getContentList().add(content);
		}
	}

	private Integer intAttribute(String value) {
		
		if (value == null) {
			return null;
		}
		
		return Integer.parseInt(value);
	}
}
